﻿using System;
using System.IO;
using System.Data;
using System.Collections;
using System.Data.OleDb;
using System.Windows.Forms;

namespace Epicor.Pub
{
    /// <summary>
    /// Excel操作类
    /// </summary>
    public static class PubFun_Excel
    {
        /// <summary>获取Excel连接字符串</summary>
        public static string GetConnStr(string ExcelFilePath)
        {
            return @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ExcelFilePath + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=2;'";
        }
        #region 数据导出至Excel文件
        /// <summary> 将数据导出至Excel文件</summary>
        /// <param name="Table">DataTable对象</param>
        /// <param name="ExcelFilePath">Excel文件路径</param>
        public static bool OutputToExcel(DataTable Table, string ExcelFilePath)
        {
            if (File.Exists(ExcelFilePath))
            {
                if (MessageBox.Show("文件已经存在,是否覆盖！", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    File.Delete(ExcelFilePath);
                }
            }
            if ((Table.TableName.Trim().Length == 0) || (Table.TableName.ToLower() == "table"))
            {
                Table.TableName = "Sheet1";
            }
            
            string TableStructStr = @"Create Table " + Table.TableName + "(";//创建表结构的SQL语句
            string connString = GetConnStr(ExcelFilePath);//连接字符串
            OleDbConnection objConn = new OleDbConnection(connString);
            //创建表结构
            OleDbCommand objCmd = new OleDbCommand();
            ArrayList DataTypeList = new ArrayList();//数据类型集合
            DataTypeList.Add("System.Decimal");
            DataTypeList.Add("System.Double");
            DataTypeList.Add("System.Int16");
            DataTypeList.Add("System.Int32");
            DataTypeList.Add("System.Int64");
            DataTypeList.Add("System.Single");
            
            int ColCount = Table.Columns.Count;//数据表的列数
            OleDbParameter[] para = new OleDbParameter[ColCount]; //创建参数
            for (int i = 0; i < Table.Columns.Count;i++ )//遍历数据表的所有列，用于创建表结构
            {
                string str = "";
                if (DataTypeList.IndexOf(Table.Columns[i].DataType.ToString()) >= 0)//如果列属于数字列，则设置该列的数据类型为double
                {
                    para[i] = new OleDbParameter("@" + Table.Columns[i].ColumnName, OleDbType.Double);
                    str = " double";
                }
                else
                {
                    para[i] = new OleDbParameter("@" + Table.Columns[i].ColumnName, OleDbType.VarChar);
                    str = " varchar";
                }
                if (i + 1 == ColCount)//如果是最后一列
                {
                    TableStructStr +="["+ Table.Columns[i].ColumnName+"]" + str + ")";
                }
                else
                {
                    TableStructStr +="["+ Table.Columns[i].ColumnName +"]"+ str + ",";
                }
                objCmd.Parameters.Add(para[i]);
            }
            try //创建Excel文件及文件结构
            {
                objCmd.Connection = objConn;
                objCmd.CommandText = TableStructStr;
                if (objConn.State == ConnectionState.Closed)
                {
                    objConn.Open();
                }
                objCmd.ExecuteNonQuery();
            }
            catch (Exception exp)
            {
                throw exp;
            }

            //插入记录的SQL语句
            string InsertSql_1 = "Insert into " + Table.TableName + " (";
            string InsertSql_2 = " Values (";
            string InsertSql = "";

            //遍历所有列，用于插入记录，在此创建插入记录的SQL语句
            for (int colID = 0; colID < ColCount; colID++)
            {
                if (colID + 1 == ColCount)  //最后一列
                {
                    InsertSql_1 +="["+ Table.Columns[colID].ColumnName + "])";
                    InsertSql_2 += "[@" + Table.Columns[colID].ColumnName + "])";
                }
                else
                {
                    InsertSql_1 += "[" + Table.Columns[colID].ColumnName + "],";
                    InsertSql_2 += "[@" + Table.Columns[colID].ColumnName + "],";
                }
            }

            InsertSql = InsertSql_1 + InsertSql_2;

            //遍历数据表的所有数据行
            for (int rowID = 0; rowID < Table.Rows.Count; rowID++)
            {
                for (int colID = 0; colID < ColCount; colID++)
                {
                    if (para[colID].DbType == DbType.Double && Table.Rows[rowID][colID].ToString().Trim() == "")
                    {
                        para[colID].Value = 0;
                    }
                    else
                    {
                        para[colID].Value = Table.Rows[rowID][colID].ToString().Trim();
                    }
                }
                try
                {
                    objCmd.CommandText = InsertSql;
                    objCmd.ExecuteNonQuery();
                }
                catch (Exception exp)
                {
                    MessageBox.Show(exp.Message);
                }
            }
            try
            {
                if (objConn.State == ConnectionState.Open)
                {
                    objConn.Close();
                }
            }
            catch (Exception exp)
            {
                throw exp;
            }
            return true;
        }

     
        #endregion

        /// <summary> 获取Excel文件数据表名称</summary>
        public static ArrayList GetExcelTables(string ExcelFileName)
        {
            DataTable dt = new DataTable();
            ArrayList TablesList = new ArrayList();
            if (File.Exists(ExcelFileName))
            {
                using (OleDbConnection conn = new OleDbConnection(GetConnStr(ExcelFileName)))
                {
                    try
                    {
                        conn.Open();
                        dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
                    }
                    catch (Exception exp)
                    {
                        throw exp;
                    }

                    //获取数据表个数
                    int tablecount = dt.Rows.Count;
                    for (int i = 0; i < tablecount; i++)
                    {
                        string tablename = dt.Rows[i][2].ToString().Trim().TrimEnd('$');
                        if (TablesList.IndexOf(tablename) < 0)
                        {
                            TablesList.Add(tablename);
                        }
                    }
                }
            }
            return TablesList;
        }

        /// <summary> 将Excel文件导出至DataTable(第一行作为表头)</summary>
        /// <param name="ExcelFilePath">Excel文件路径</param>
        /// <param name="TableName">数据表名，如果数据表名错误，默认为第一个数据表名</param>
        public static DataTable InputFromExcel(string ExcelFilePath, string TableName=null)
        {
            if (!File.Exists(ExcelFilePath))
            {
                throw new Exception("Excel文件不存在！");
            }
            //如果数据表名不存在，则数据表名为Excel文件的第一个数据表
            ArrayList TableList = new ArrayList();
            TableList = GetExcelTables(ExcelFilePath);

            if (TableName == null || TableList.IndexOf(TableName)<0)
            {
                TableName = TableList[0].ToString().Trim();
            }
            DataTable table = new DataTable();
            OleDbConnection dbcon = new OleDbConnection(GetConnStr(ExcelFilePath));
            OleDbCommand cmd = new OleDbCommand("select * from [" + TableName + "$]", dbcon);
            OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
            try
            {
                if (dbcon.State == ConnectionState.Closed)
                {
                    dbcon.Open();
                }
                adapter.Fill(table);
            }
            catch (Exception exp)
            {
                throw exp;
            }
            finally
            {
                if (dbcon.State == ConnectionState.Open)
                {
                    dbcon.Close();
                }
            }
            return table;
        }

        /// <summary>获取Excel文件指定数据表的列名称</summary>
        /// <param name="ExcelFileName">Excel文件名</param>
        /// <param name="TableName">数据表名</param>
        public static ArrayList GetExcelTableColumns(string ExcelFileName, string TableName)
        {
            DataTable dt = new DataTable();
            ArrayList ColsList = new ArrayList();
            if (File.Exists(ExcelFileName))
            {
                using (OleDbConnection conn = new OleDbConnection(GetConnStr(ExcelFileName)))
                {
                    conn.Open();
                    dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new object[] { null, null, TableName, null });

                    //获取列个数
                    int colcount = dt.Rows.Count;
                    for (int i = 0; i < colcount; i++)
                    {
                        string colname = dt.Rows[i]["Column_Name"].ToString().Trim();
                        ColsList.Add(colname);
                    }
                }
            }
            return ColsList;
        }
    }
}